import * as echarts from 'echarts';
import "echarts-liquidfill/src/liquidFill.js";

const setPie = ({ dom, data, resize, title }) => {
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }
    const legendData = [];
    data.forEach(itme => {
        legendData.push(itme.name)
    });
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: legendData,
            textStyle: {
                width: 70,
                overflow: 'truncate',
                ellipsis: '...'
            }
        },
        series: [
            {
                name: title,
                type: 'pie',
                radius: ['25%', '80%'],  // 调整内外半径比例
                center: ['40%', '50%'],
                itemStyle: {
                    borderRadius: 0,  // 移除圆角以保持标准扇形
                    borderWidth: 1,
                    borderColor: '#fff'
                },
                label: {
                    show: false,
                },
                labelLine: {
                    show: false
                },
                // 确保数据按值排序，使大小差异更明显
                data: [...data].sort((a, b) => b.value - a.value),
                // 保持圆形但区块大小不同
                avoidLabelOverlap: true,
                stillShowZeroSum: false
            },
        ]
    }
    myChart.setOption(option)
}

const setRoundPie = ({ dom, data, resize, title }) => {
    if (!dom) {
        return;
    }
    let myChart = echarts.getInstanceByDom(dom);
    if (!myChart) {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return;
    }
    const legendData = data.map(item => item.name);
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: legendData,
            textStyle: {
                width: 70,
                overflow: 'truncate',
                ellipsis: '...'
            }
        },
        series: [
            {
                name: title,
                type: 'pie',
                radius: ['25%', '80%'],  // 调整内外半径比例
                center: ['40%', '50%'],
                // 移除roseType以保持标准圆形
                itemStyle: {
                    borderRadius: 0,  // 移除圆角以保持标准扇形
                    borderWidth: 1,
                    borderColor: '#fff'
                },
                label: {
                    show: false,
                },
                labelLine: {
                    show: false
                },
                // 确保数据按值排序，使大小差异更明显
                data: [...data].sort((a, b) => b.value - a.value),
                // 保持圆形但区块大小不同
                avoidLabelOverlap: true,
                stillShowZeroSum: false
            }
        ]
    };

    myChart.setOption(option, true);  // 使用true不合并旧选项

    // 添加窗口大小变化监听
    window.addEventListener('resize', () => myChart.resize());

    return () => {
        window.removeEventListener('resize', () => myChart.resize());
    };
};

//考核任务详情 柱状图
function setLineChart(id, data, resize) {
    let barData = [];
    let lineData = [];
    let times = [];
    let max = "";
    let maxData = [];
    if (data.length > 0) {
        for (var i = data.length - 1; i >= 0; i--) {
            times.unshift(data[i].name)
            lineData.unshift(data[i].value)
            maxData.push(data[i].value)
        }
        max = maxData.sort((a, b) => { return b - a })[0];
        for (var j = 0; j < maxData.length; j++) {
            barData.push(max + 10)
        }
    }
    const dom = document.getElementById(id);
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }
    let option = {
        backgroundColor: 'transparent',
        grid: {
            top: '40',
            right: '30',
            left: '30',
            bottom: '40' //图表尺寸大小
        },
        tooltip: {
            trigger: 'axis',
            // backgroundColor:"transparent",
            padding: 0,
            formatter: (params) => {
                return `<div class="line-chart-tooltip">${params[0].axisValue} ：${params[0].value}</div>`
            }
        },
        xAxis: [{
            type: 'category',
            color: '#59588D',
            data: times,
            axisLabel: {
                margin: 10,
                color: '#999',
                textStyle: {
                    fontSize: 10
                },
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(107,107,107,0.37)',
                }
            },
            axisTick: {
                show: false
            },
        }],
        yAxis: [{
            axisLabel: {
                formatter: max,
                color: '#999',
                textStyle: {
                    fontSize: 12
                },
            },
            minInterval: 1,
            axisLine: {
                lineStyle: {
                    color: 'rgba(107,107,107,0.37)',
                }
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(131,101,101,0.2)',
                    type: 'dashed',
                }
            }
        }],
        series: [{
            type: 'bar',
            data: lineData,
            barWidth: '10px',
            showBackground: true,
            backgroundStyle: {
                color: '#ECF6FF'
            },
            itemStyle: {
                normal: {
                    color: function (params) { //展示正值的柱子，负数设为透明
                        let colorArr = params.value > 0 ? ['#1DD1FF', '#799CFD'] : ['#ECF6FF', '#ECF6FF']
                        return new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: colorArr[0] // 0% 处的颜色
                        }, {
                            offset: 1,
                            color: colorArr[1] // 100% 处的颜色
                        }], false)
                    },
                    barBorderRadius: [30, 30, 0, 0] //圆角大小
                },
            }
        }]
    };
    myChart.setOption(option)
}

//水球图
function setLiquidfill(id, ratios, textName, resize) {
    const dom = document.getElementById(id);
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    var ratio = Math.floor(ratios * 100) / 100; //占比数值  总数为100
    var ratioLength = 3; //波浪数量
    var ratioArr = [];
    var ratioColor = ["#1890ff"]; //波浪内颜色
    for (var ratioIndex = 0; ratioIndex < ratioLength; ratioIndex++) {
        ratioArr.push(ratio / 100)
    }
    if (resize) {
        myChart.resize();
        return
    }
    var option = {
        title: {
            text: textName,
            left: 'center',
            top: '15%',
            textStyle: {
                fontWeight: 'normal',
                fontSize: 16,
                color: '#333',
            },
        },
        series: [{
            type: 'liquidFill',
            radius: '70%',
            center: textName ? ['50%', '60%'] : ['50%', '50%'],
            color: ratioColor,
            data: ratioArr,
            backgroundStyle: {
                borderWidth: 1,
                color: '#fff'
            },
            label: {
                normal: {
                    formatter: ratio.toFixed(2) + '%',
                    textStyle: {
                        fontSize: 24,
                    }
                }
            },
            outline: {
                show: false,
            }
        }]
    }
    myChart.setOption(option)
}
function setScoreRank(id, data) {
    const dom = document.getElementById(id);
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    // var charts = {
    //     // 按顺序排列从大到小
    //     cityList: ["38号点（1）", "38号点（2）", "15号点", "16号点", "24号点"],
    //     cityData: [7500, 6200, 5700, 4200, 3500],
    // };
    var top10CityList = [];
    var top10CityData = [];
    // var color = [
    //     "rgba(248,195,248",
    //     "rgba(100,255,249",
    //     "rgba(135,183,255",
    //     "rgba(248,195,248",
    //     "rgba(100,255,249",
    // ];
    var color = [
        "rgba(24,144,255",
    ]
    let lineY = [];
    data = data.map(x => ({ ...x, count: Number(x.count.toFixed()) }));
    for (let i = 0; i < data.length; i++) {
        let x = i;
        if (x > color.length - 1) {
            x = color.length - 1;
        }
        top10CityList.push(data[i].name);
        top10CityData.push(data[i].count + 10)
        let list = {
            name: data[i].name,
            color: color[x] + ")",
            value: data[i].count + 10,
            itemStyle: {
                normal: {
                    show: true,
                    color: new echarts.graphic.LinearGradient(
                        0,
                        0,
                        1,
                        0,
                        [
                            {
                                offset: 0,
                                color: color[x] + ", 0.3)",
                            },
                            {
                                offset: 1,
                                color: color[x] + ", 1)",
                            },
                        ],
                        false
                    ),
                    barBorderRadius: 10,
                },
                emphasis: {
                    shadowBlur: 15,
                    shadowColor: "rgba(0, 0, 0, 0.1)",
                },
            },
        };
        lineY.push(list);
    }
    let option = {
        // backgroundColor:'#000',
        title: {
            show: false,
        },
        tooltip: {
            trigger: 'item',
            formatter: function (data) {
                let count = data.data.value - 10;
                return `${data.data.name}积分:${count}`
            },
        },
        grid: {
            borderWidth: 0,
            top: "10%",
            left: "5%",
            right: "15%",
            bottom: "3%",
        },
        color: color,
        yAxis: [
            {
                type: "category",
                inverse: true,
                axisTick: {
                    show: false,
                },
                axisLine: {
                    show: false,
                },
                axisLabel: {
                    show: false,
                    inside: false,
                },
                data: top10CityList
            },
            {
                type: "category",
                axisLine: {
                    show: false,
                },
                axisTick: {
                    show: false,
                },
                axisLabel: {
                    show: true,
                    inside: false,
                    textStyle: {
                        color: "#666",
                        fontSize: "12",
                        // fontFamily: "PingFangSC-Regular",
                    },
                    formatter: function (val) {
                        let count = val - 10;
                        return count + '分';
                    },
                },
                splitArea: {
                    show: false,
                },
                splitLine: {
                    show: false,
                },
                data: top10CityData.reverse(),
            },
        ],
        xAxis: {
            type: "value",
            axisTick: {
                show: false,
            },
            axisLine: {
                show: false,
            },
            splitLine: {
                show: false,
            },
            axisLabel: {
                show: false,
            },
        },
        series: [
            {
                name: "",
                type: "bar",
                zlevel: 2,
                barWidth: "10px",
                data: lineY,
                animationDuration: 1500,
                label: {
                    normal: {
                        color: "#666",
                        show: true,
                        position: [0, "-20px"],
                        textStyle: {
                            fontSize: 14,
                        },
                        width: 240,
                        overflow: 'truncate',
                        ellipsis: '...',
                        formatter: function (a, b) {
                            return `${a.name}积分`;
                        },
                    },
                },
            },
        ],
        animationEasing: "cubicOut",
    };
    myChart.setOption(option)
}

//理论题目分类占比
function setThroryPie(id, datas, resize) {
    const dom = document.getElementById(id);
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }
    var option = {
        color: ["#9FE6B8", "#FFDB5C", "#FF9F7F"],
        tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} ({d}%)'
        },
        series: [
            {
                name: "",
                type: "pie",
                radius: ["20%", "40%"],
                center: ["50%", "50%"],
                roseType: "radius",
                label: {
                    show: true
                },
                labelLine: {
                    show: true
                },
                data: datas,
            },
        ],
    };
    myChart.setOption(option)
}

// 视频播放时长柱状图
function setRank(id, data) {
    const dom = document.getElementById(id);
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    // var charts = {
    //     // 按顺序排列从大到小
    //     cityList: ["38号点（1）", "38号点（2）", "15号点", "16号点", "24号点"],
    //     cityData: [7500, 6200, 5700, 4200, 3500],
    // };
    var top10CityList = [];
    var top10CityData = [];
    // var color = [
    //     "rgba(248,195,248",
    //     "rgba(100,255,249",
    //     "rgba(135,183,255",
    //     "rgba(248,195,248",
    //     "rgba(100,255,249",
    // ];
    var color = [
        "rgba(24,144,255",
    ]
    let lineY = [];
    for (let i = 0; i < data.length; i++) {
        let x = i;
        if (x > color.length - 1) {
            x = color.length - 1;
        }
        top10CityList.push(data[i].name);
        top10CityData.push(data[i].count + 10)
        let list = {
            name: data[i].name,
            color: color[x] + ")",
            value: data[i].count + 10,
            itemStyle: {
                normal: {
                    show: true,
                    color: new echarts.graphic.LinearGradient(
                        0,
                        0,
                        1,
                        0,
                        [
                            {
                                offset: 0,
                                color: color[x] + ", 0.3)",
                            },
                            {
                                offset: 1,
                                color: color[x] + ", 1)",
                            },
                        ],
                        false
                    ),
                    barBorderRadius: 10,
                },
                emphasis: {
                    shadowBlur: 15,
                    shadowColor: "rgba(0, 0, 0, 0.1)",
                },
            },
        };
        lineY.push(list);
    }
    let option = {
        // backgroundColor:'#000',
        title: {
            show: false,
        },
        tooltip: {
            trigger: 'item',
            formatter: function (data) {
                let time = '';
                let count = data.data.value - 10;
                if (count < 60) {
                    time = count + '秒'
                } else if (count < 3600) {
                    time = Math.floor(count / 60) + '分钟'
                } else {
                    time = Math.floor(count / 3600) + '小时'
                }
                return `${data.data.name}学习时长:${time}`
            },
        },
        grid: {
            borderWidth: 0,
            top: "10%",
            left: "5%",
            right: "15%",
            bottom: "3%",
        },
        color: color,
        yAxis: [
            {
                type: "category",
                inverse: true,
                axisTick: {
                    show: false,
                },
                axisLine: {
                    show: false,
                },
                axisLabel: {
                    show: false,
                    inside: false,
                },
                data: top10CityList,
            },
            {
                type: "category",
                axisLine: {
                    show: false,
                },
                axisTick: {
                    show: false,
                },
                axisLabel: {
                    show: true,
                    inside: false,
                    textStyle: {
                        color: "#666",
                        fontSize: "12",
                        // fontFamily: "PingFangSC-Regular",
                    },
                    formatter: function (val) {
                        let data = '';
                        let count = val - 10;
                        if (count < 60) {
                            data = count + '秒'
                        } else if (count < 3600) {
                            data = Math.floor(count / 60) + '分'
                        } else {
                            data = Math.floor(count / 3600) + '小时'
                        }
                        return data;
                    },
                },
                splitArea: {
                    show: false,
                },
                splitLine: {
                    show: false,
                },
                data: top10CityData.reverse(),
            },
        ],
        xAxis: {
            type: "value",
            axisTick: {
                show: false,
            },
            axisLine: {
                show: false,
            },
            splitLine: {
                show: false,
            },
            axisLabel: {
                show: false,
            },
        },
        series: [
            {
                name: "",
                type: "bar",
                zlevel: 2,
                barWidth: "10px",
                data: lineY,
                animationDuration: 1500,
                label: {
                    normal: {
                        color: "#666",
                        show: true,
                        position: [0, "-20px"],
                        textStyle: {
                            fontSize: 14,
                        },
                        width: 240,
                        overflow: 'truncate',
                        ellipsis: '...',
                        formatter: function (a, b) {
                            return `${a.name}学习时长`;
                        },
                    },
                },
            },
        ],
        animationEasing: "cubicOut",
    };
    myChart.setOption(option)
}

// 折线图
function setLine(id, data, resize) {
    const dom = document.getElementById(id);
    if (!dom) {
        return
    }
    // 根据dom获取echart实例
    let myChart = echarts.getInstanceByDom(dom);
    // 如果实例不存在，则初始化
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    // 如果需要重置图表大小，则重置
    if (resize) {
        myChart.resize();
        return
    }
    // 获取图例
    let legend = [];
    // 获取系列 系列就是图表的每一根线
    let series = [];
    // 遍历数据
    (data.yData || []).forEach(item => {
        // 获取图例
        legend.push(item.name);
        // 获取系列
        series.push({
            name: item.name,
            type: 'line',

            data: item.data
        })
    })
    var option = {
        title: {
            text: data.title
        },
        // 提示框
        tooltip: {
            // 触发类型
            trigger: 'axis'
        },
        // 图例
        legend: {
            // 数据
            data: legend,
            // 是否显示
            show: legend.length > 1 ? true : false,
            // 位置
            right: 20
        },
        // 网格
        grid: {
            // 左边距
            left: '3%',
            // 右边距
            right: '4%',
            // 下边距
            bottom: '3%',
            // 是否包含标签
            containLabel: true
        },
        // x轴
        xAxis: {
            // 类型
            type: 'category',
            // 是否包含标签
            boundaryGap: false,
            // 数据
            data: data.xData
        },
        // y轴
        yAxis: {
            // 类型
            type: 'value'
        },
        // 系列
        series: series
    };
    // 设置图表
    myChart.setOption(option)
}

//渐变折线图
function setGradientLine(id, data, resize) {
    const dom = document.getElementById(id);
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }

    // 处理数据
    const xAxisData = data.xData || ["6.1", "6.2", "6.3", "6.4", "6.5", "6.6", "6.7"];
    const seriesData = data.yData || [90, 105, 84, 125, 110, 92, 98];
    const seriesName = data.name || "异常流量";
    const lineColor = data.lineColor || "#3deaff";
    const areaColorStart = data.areaColorStart || "rgba(61,234,255, 0.9)";
    const areaColorEnd = data.areaColorEnd || "rgba(61,234,255, 0)";
    const shadowColor = data.shadowColor || "rgba(53,142,215, 0.9)";
    const yAxisMax = data.yAxisMax || 140;
    const yAxisSplitNumber = data.yAxisSplitNumber || 7;

    // 默认使用白色背景
    const backgroundColor = data.backgroundColor || "#ffffff";
    // 在白色背景下使用的轴线颜色
    const axisLineColor = data.axisLineColor || "#e0e0e0";
    // 在白色背景下使用的文字颜色
    const textColor = data.textColor || "#333333";

    const option = {
        backgroundColor: backgroundColor,
        tooltip: {
            trigger: 'axis',
            formatter: data.tooltipFormatter || '{a} <br/>{b} : {c}'
        },
        grid: {
            top: data.gridTop || "8%",
            left: data.gridLeft || "1%",
            right: data.gridRight || "1%",
            bottom: data.gridBottom || "1%",
            containLabel: true,
        },
        xAxis: [
            {
                type: "category",
                boundaryGap: false,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: axisLineColor,
                    },
                },
                axisLabel: {
                    textStyle: {
                        color: textColor,
                        margin: 15,
                    },
                    rotate: data.offset || 0,
                },
                axisTick: { show: false },
                data: xAxisData,
            },
        ],
        yAxis: [
            {
                type: "value",
                minInterval: 1,
                max: yAxisMax,
                splitNumber: yAxisSplitNumber,
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: axisLineColor,
                    },
                },
                axisLine: { show: false },
                axisLabel: {
                    margin: 20,
                    textStyle: {
                        color: textColor,
                    },
                },
                axisTick: { show: false },
            },
        ],
        series: [
            {
                name: seriesName,
                type: "line",
                smooth: true,
                symbolSize: 0,
                lineStyle: {
                    normal: {
                        color: lineColor,
                    },
                },
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            0,
                            0,
                            0,
                            1,
                            [
                                { offset: 0, color: areaColorStart },
                                { offset: 0.7, color: areaColorEnd },
                            ],
                            false
                        ),
                        shadowColor: shadowColor,
                        shadowBlur: 20,
                    },
                },
                data: seriesData,
            },
        ],
    };

    myChart.setOption(option);
}

//雷达图
function setRadarChart(id, data, resize) {
    const dom = document.getElementById(id);
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }

    // 处理数据
    const values = data.values || [582, 421.2, 622.1, 625.3, 265, 224];
    const indicator = data.indicator || [
        { name: "套餐1", max: 1000 },
        { name: "套餐2", max: 1000 },
        { name: "套餐3", max: 1000 },
        { name: "套餐4", max: 1000 },
        { name: "套餐5", max: 1000 },
        { name: "套餐6", max: 1000 }
    ];
    const unit = data.unit || "万";
    const nameTextColor = data.nameTextColor || "#BCDCFF";
    const valueTextColor = data.valueTextColor || "#8E88FE";
    const mainAreaColor = data.mainAreaColor || "#7D77F1";
    const mainAreaOpacity = data.mainAreaOpacity || 0.6;
    const pointBorderColor = data.pointBorderColor || "#F2F063";
    const backgroundColors = data.backgroundColors || ["#4175F5", "#2C72C8", "#4175F5", "#4175F5", "#4175F5", "#4175F5"];
    const backgroundOpacities = data.backgroundOpacities || [0.06, 0.12, 0.18, 0.19, 0.17, 0.16, 0.13];
    const backgroundLevels = data.backgroundLevels || [1000, 900, 800, 700, 600, 500, 400];

    // 构建背景层系列
    const backgroundSeries = backgroundLevels.map((level, index) => {
        const colorIndex = index < backgroundColors.length ? index : backgroundColors.length - 1;
        return {
            type: "radar",
            data: [[level, level, level, level, level, level]],
            symbol: "none",
            lineStyle: {
                width: 0,
            },
            itemStyle: {
                color: backgroundColors[colorIndex],
            },
            areaStyle: {
                color: backgroundColors[colorIndex],
                opacity: backgroundOpacities[index],
            },
        };
    });

    const option = {
        radar: {
            center: ['50%', '60%'],  // 将中心点下移，默认是 ['50%', '50%']
            radius: '70%',           // 控制雷达图大小，确保不会太贴近边缘
            name: {
                formatter: function (name) {
                    return "{a|" + name + "}";
                },
                textStyle: {
                    rich: {
                        a: {
                            color: nameTextColor,
                            fontSize: 14,
                            fontWeight: 600,
                            fontFamily: "Source Han Sans CN",
                        }
                    },
                },
            },
            nameGap: 0,
            indicator: indicator,
            splitLine: {
                show: false,
            },
            splitArea: {
                show: false,
            },
            axisLine: {
                show: false,
            },
        },
        series: [
            {
                type: "radar",
                data: [values],
                label: {
                    show: true,
                    formatter: function (params) {
                        return params.value + unit;
                    },
                    color: valueTextColor,
                    align: "right",
                    distance: 10,
                },
                symbolSize: [6, 6],
                lineStyle: {
                    width: 0,
                },
                itemStyle: {
                    borderWidth: 1,
                    color: "#fff",
                    borderColor: pointBorderColor,
                },
                areaStyle: {
                    color: mainAreaColor,
                    opacity: mainAreaOpacity,
                },
            },
            ...backgroundSeries
        ],
    };

    myChart.setOption(option);
}

const setTaskProgress = ({ dom, data, resize, title }) => {
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }
    const option = {
        series: [{
            type: 'pie',
            radius: ['67%', '78%'],  // 环形大小
            startAngle: 90,         // 起始角度
            clockwise: true,        // 逆时针
            hoverAnimation: false,   // 禁用悬浮动画
            itemStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 1,
                    y2: 0,
                    colorStops: [{
                        offset: 0, color: '#4D97F1' // 渐变起始色
                    }, {
                        offset: 1, color: '#59FFFF' // 渐变结束色
                    }]
                },
                shadowBlur: 6,        // 发光模糊度
                shadowColor: '#59FFFF' // 发光颜色
            },
            label: {
                show: false
            },
            data: [{
                value: data,             // 当前进度值
                itemStyle: {
                    borderWidth: 0,
                    borderColor: '#000'
                }
            }, {
                // 剩余部分
                value: 100 - data,
                itemStyle: {
                    color: 'rgba(240,240,240,0.1)'
                }
            }]
        },
        // 发光层
        {
            type: 'pie',
            radius: ['67%', '78%'],
            startAngle: 90,
            clockwise: true,
            hoverAnimation: false,
            itemStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 1,
                    y2: 0,
                    colorStops: [{
                        offset: 0, color: 'rgba(77,151,241,0.3)' // 半透明渐变
                    }, {
                        offset: 1, color: 'rgba(89,255,255,0.3)'
                    }]
                },
                shadowBlur: 20,        // 更大的模糊度
                shadowColor: '#59FFFF'
            },
            label: { show: false },
            data: [{
                value: data,
                itemStyle: {
                    borderWidth: 0
                }
            }, {
                value: 100 - data,
                itemStyle: {
                    // color: 'transparent'
                }
            }]
        }],
    };
    myChart.setOption(option)
}

const setTendencyChart = ({ dom, resize }, data = {}) => {
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }

    // 从传入的data参数中获取数据
    const xData = data.xData || ['00:00', '00:05', '00:10', '00:15', '00:20', '00:25', '00:30'];
    const yData = data.yData || [20, 25, 40, 65, 70, 75, 78];
    const yAxisMax = data.yAxisMax || 100;
    const interval = Math.ceil(yAxisMax / 5) || 20;

    const option = {
        tooltip: {
            trigger: 'axis',
            borderRadius: 0, // 圆角
            padding: [0, 0], // 内边距
            textStyle: {
                color: '#fff',
                fontSize: 14
            },
            formatter: (params) => {
                return `<div style="text-align:left;padding:10px;background-image: linear-gradient(to bottom, #4058a8, #36185f);box-shadow: 0 2px 8px rgba(24,144,255,0.4);">
                  <div style="margin-bottom:6px;font-weight:500">${params[0].axisValue}</div>
                  <div>${params[0].value}</div>
                </div>`
            },
            axisPointer: {
                type: 'cross',
            }
        },
        grid: {
            top: '4%',
            left: '1%',
            right: '3%',
            bottom: '0%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: xData  // 使用传入的xData
            }
        ],
        yAxis: [
            {
                type: 'value',
                min: 0,          // 最小值
                max: yAxisMax,   // 使用传入的yAxisMax
                interval: interval,    // 动态计算间隔
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.15)',
                        type: 'solid'
                    }
                },
                axisLabel: {
                    formatter: function (value) {
                        return value; // 直接显示数值
                    }
                }
            }
        ],
        series: [
            {
                name: data.name || '访问次数',  // 使用传入的name
                type: 'line',
                stack: 'Total',
                smooth: true,
                lineStyle: {
                    width: 2,
                    color: new echarts.graphic.LinearGradient(
                        0, 0, 1, 0,
                        [
                            { offset: 0, color: '#1968FF' },
                            { offset: 1, color: '#3DE6FF' }
                        ]
                    ),
                    shadowBlur: 12,
                    shadowColor: 'rgba(61, 230, 255, 0.8)',
                    opacity: 0.9
                },
                showSymbol: false,
                areaStyle: {
                    opacity: 0.8,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(61, 230, 255, 1)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(25, 104, 255, 0)'
                        }
                    ])
                },
                emphasis: {
                    focus: 'series',
                    lineStyle: {
                        shadowBlur: 15,
                        shadowColor: 'rgba(61, 230, 255, 1)'
                    }
                },
                data: yData  // 使用传入的yData
            }
        ]
    };
    myChart.setOption(option)
}

// 智能蓝军雷达图
function setIntelligenceRadarChart({ dom, resize, title }, data = []) {
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }

    // 处理传入的数据，形式为 [{key: '病毒攻击', value: 60}, ...]
    // 确保数据不为空
    if (!data || data.length === 0) {
        data = [
            { key: '病毒攻击', value: 60 },
            { key: '入侵渗透', value: 80 },
            { key: '隐蔽迂回', value: 50 },
            { key: '人员渗透', value: 70 },
            { key: '权限提升', value: 40 },
            { key: '安装部署', value: 90 },
            { key: '数据获取', value: 75 },
            { key: '系统操控', value: 65 },
            { key: '流量牵引', value: 55 }
        ];
    }



    // 提取指标名称和值
    const indicatorNames = data.map(item => item.key);
    const values = data.map(item => item.value);

    // 计算数据的最大值，用于动态设置刻度
    const maxValue = Math.max(...values, 5) * 1.2; // 确保最大值至少为10，并留出20%的空间

    // 创建指标配置 - 使用实际数据创建
    const indicator = indicatorNames.map(name => ({
        name: name,
        max: maxValue  // 动态设置最大值
    }));

    // 构建雷达图选项
    const option = {
        title: title ? {
            text: title,
            textStyle: {
                fontSize: 14
            },
            left: 'center',
            top: 0
        } : undefined,
        tooltip: {
            trigger: 'item',
            formatter: (params) => {
                // 直接从原始数据中获取值和名称
                return data.map(item => `${item.key}: ${item.value}`).join('<br/>');
            }
        },
        radar: {
            center: ['50%', '60%'],  // 将中心点下移，默认是 ['50%', '50%']
            radius: '70%',           // 控制雷达图大小，确保不会太贴近边缘
            name: {
                formatter: function (name) {
                    return "{a|" + name + "}";
                },
                textStyle: {
                    rich: {
                        a: {
                            color: '#333',
                            fontSize: 14,
                            fontWeight: 600,
                            fontFamily: "Source Han Sans CN",
                        }
                    },
                },
            },
            nameGap: 0,
            indicator: indicator,
            splitNumber: 4,  // 分4个等级
            splitArea: {
                areaStyle: {
                    color: ['rgba(255, 255, 255, 0.1)', 'rgba(255, 255, 255, 0.2)',
                        'rgba(255, 255, 255, 0.3)', 'rgba(255, 255, 255, 0.4)'],
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                    shadowBlur: 10
                }
            },
            axisName: {
                color: '#333',
                fontSize: 12  // 轴名称字体大小
            },
            axisLine: {
                lineStyle: {
                    color: '#ddd'  // 轴线颜色
                }
            },
            splitLine: {
                lineStyle: {
                    color: '#ddd'  // 分割线颜色
                }
            }
        },
        series: [
            {
                type: 'radar',
                data: [
                    {
                        value: values,
                        name: '能力评估',
                        symbol: 'none',  // 不显示点
                        lineStyle: {
                            width: 2,
                            color: '#8A79FF'  // 线条颜色，根据图片调整
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: 'rgba(138, 121, 255, 0.7)'  // 图片中紫色区域
                                }, {
                                    offset: 1,
                                    color: 'rgba(138, 121, 255, 0.2)'
                                }]
                            }
                        },
                        label: {
                            show: true,
                            formatter: '{c}',
                            color: '#333'
                        }
                    }
                ]
            }
        ]
    };

    myChart.setOption(option);

}

function setPieChart({ dom, resize, title }, data = []) {
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }
    var color = [
        "#00ffff",
        "#00cfff",
        "#006ced",
        "#ffe000",
        "#ffa800",
        "#ff5b00",
        "#ff3000",
    ];
    var seriesOption = [
        {
            name: "",
            type: "pie",
            clockWise: false,
            radius: ['45%', '55%'],  // 改为百分比，适应小容器
            hoverAnimation: false,
            center: ['40%', '50%'],  // 添加中心点，为图例留空间
            itemStyle: {
                normal: {
                    label: {
                        show: true,
                        position: "outside",
                        color: "#ddd",
                        fontSize: 15,  // 减小字体
                        formatter: function (params) {
                            var percent = 0;
                            var total = 0;
                            for (var i = 0; i < data.length; i++) {
                                total += data[i].value;
                            }
                            percent = ((params.value / total) * 100).toFixed(0);
                            if (params.name !== "") {
                                return params.name + "\n" + percent + "%";  // 简化显示
                            } else {
                                return "";
                            }
                        },
                    },
                    labelLine: {
                        length: 10,    // 减短引导线
                        length2: 20,   // 减短引导线
                        show: true,
                        color: "#00ffff",
                    },
                },
            },
            data: data,
        },
    ];
    const option = {
        backgroundColor: "transparent",  // 改为透明背景
        color: color,

        tooltip: {
            show: true,  // 开启提示框
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
            icon: "circle",
            orient: "horizontal",  // 垂直排列
            data: data.map(item => item.name),
            left: 10,      // 调整图例位置
            bottom: 0,        // 调整图例位置
            textStyle: {
                color: "#fff",
                fontSize: 15,  // 减小图例字体
            },
            itemGap: 5,     // 减小间距
            itemWidth: 8,   // 减小图例标记大小
            itemHeight: 8,
        },
        toolbox: {
            show: false,
        },
        series: seriesOption,
    };
    myChart.setOption(option);
}

function setULineChart({ dom, resize, title }, data = []) {
    if (!dom) {
        return
    }
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    if (resize) {
        myChart.resize();
        return
    }
    const option = {
        backgroundColor: "transparent",
        tooltip: {},
        grid: {
            top: "8%",
            left: "1%",
            right: "1%",
            bottom: "8%",
            containLabel: true,
        },
        xAxis: [
            {
                type: "category",
                boundaryGap: false,
                axisLine: {
                    //坐标轴轴线相关设置。数学上的x轴
                    show: true,
                    lineStyle: {
                        color: "#233e64",
                    },
                },
                axisLabel: {
                    //坐标轴刻度标签的相关设置
                    textStyle: {
                        color: "#6a9cd5",
                        margin: 15,
                    },
                },
                axisTick: { show: false },
                data: data.map(item => item.name),
            },
        ],
        yAxis: [
            {
                type: "value",
                min: 0,
                max: 100,
                splitNumber: 7,
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: "#233e64",
                    },
                },
                axisLine: { show: false },
                axisLabel: {
                    margin: 20,
                    textStyle: {
                        color: "#6a9cd5",
                    },
                },
                axisTick: { show: false },
            },
        ],
        series: [
            {
                name: "异常流量",
                type: "line",
                smooth: true, //是否平滑曲线显示
                // 			symbol:'circle',  // 默认是空心圆（中间是白色的），改成实心圆
                symbolSize: 0,

                lineStyle: {
                    normal: {
                        color: "#3deaff", // 线条颜色
                    },
                },
                areaStyle: {
                    //区域填充样式
                    normal: {
                        //线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
                        color: new echarts.graphic.LinearGradient(
                            0,
                            0,
                            0,
                            1,
                            [
                                { offset: 0, color: "rgba(61,234,255, 0.9)" },
                                { offset: 0.7, color: "rgba(61,234,255, 0)" },
                            ],
                            false
                        ),

                        shadowColor: "rgba(53,142,215, 0.9)", //阴影颜色
                        shadowBlur: 20, //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
                    },
                },
                data: data.map(item => item.value),
            },
        ],
    };

    myChart.setOption(option);

}

// 地图数据缓存
let chinaMapCache = null;
let isMapRegistered = false;

// 中国地图
function setChinaMap({ dom, resize, title, data = [] }) {
    if (!dom) {
        return
    }
    
    let myChart = echarts.getInstanceByDom(dom);
    if ((myChart ?? '') === '') {
        myChart = echarts.init(dom);
    }
    
    if (resize) {
        // 使用防抖优化resize性能
        clearTimeout(myChart._resizeTimer);
        myChart._resizeTimer = setTimeout(() => {
            myChart.resize();
        }, 100);
        return
    }

    // 计算数据的最大值，用于动态设置visualMap
    const maxValue = data.length > 0 ? Math.max(...data.map(item => item.value)) : 100;
    const minValue = data.length > 0 ? Math.min(...data.map(item => item.value)) : 0;

    // 渲染图表的函数
    const renderChart = (geoJson) => {
        // 只有在未注册时才注册地图
        if (!isMapRegistered) {
            echarts.registerMap('china', geoJson);
            isMapRegistered = true;
        }
        
        const option = {
            backgroundColor: 'transparent',
            title: {
                text: title || '全国分布情况',
                left: 'center',
                top: 20,
                textStyle: {
                    color: '#ffffff',
                    fontSize: 20,
                    fontWeight: 'bold',
                    textShadowColor: 'rgba(59, 130, 246, 0.5)',
                    textShadowBlur: 3
                }
            },
            // 添加图例配置
            legend: {
                show: true,
                data: ['人员分布'],
                left: 'right',
                top: 60,
                textStyle: {
                    color: '#e2e8f0',
                    fontSize: 14
                },
                icon: 'rect',
                itemWidth: 15,
                itemHeight: 10
            },
            tooltip: {
                trigger: 'item',
                backgroundColor: 'rgba(30, 58, 138, 0.95)',
                borderColor: '#3b82f6',
                borderWidth: 2,
                textStyle: {
                    color: '#ffffff',
                    fontSize: 14
                },
                formatter: function (params) {
                    if (params.data && params.data.value !== undefined) {
                        return `<div style="padding: 12px; border-radius: 8px; background: linear-gradient(135deg, rgba(30, 58, 138, 0.9), rgba(59, 130, 246, 0.9));">
                            <div style="font-weight: bold; margin-bottom: 8px; font-size: 16px; color: #ffffff;">${params.name}</div>
                            <div style="display: flex; align-items: center;">
                                <div style="width: 8px; height: 8px; background: #60a5fa; border-radius: 50%; margin-right: 8px;"></div>
                                <span>人员数量: <span style="color: #93c5fd; font-weight: bold;">${params.data.value}</span> 人</span>
                            </div>
                        </div>`;
                    } else {
                        return `<div style="padding: 12px; border-radius: 8px; background: linear-gradient(135deg, rgba(30, 58, 138, 0.9), rgba(59, 130, 246, 0.9));">
                            <div style="font-weight: bold; margin-bottom: 8px; font-size: 16px; color: #ffffff;">${params.name}</div>
                            <div style="color: #94a3b8;">暂无人员数据</div>
                        </div>`;
                    }
                }
            },
            visualMap: {
                min: minValue,
                max: maxValue,
                left: 30,
                bottom: 40,
                text: ['高', '低'],
                textStyle: {
                    color: '#e2e8f0',
                    fontSize: 14,
                    fontWeight: 'bold'
                },
                calculable: true,
                orient: 'vertical',
                itemWidth: 20,
                itemHeight: 120,
                inRange: {
                    color: [
                        '#0f172a',  // 最深的蓝黑色 - 最低值
                        '#1e293b',  // 深蓝灰
                        '#334155',  // 蓝灰
                        '#0f3460',  // 深蓝色
                        '#1e40af',  // 标准深蓝
                        '#2563eb',  // 蓝色
                        '#3b82f6',  // 亮蓝
                        '#60a5fa',  // 天蓝
                        '#93c5fd'   // 浅蓝 - 最高值
                    ]
                },
                backgroundColor: 'rgba(15, 23, 42, 0.9)',
                borderColor: '#3b82f6',
                borderWidth: 2,
                borderRadius: 8,
                padding: [8, 12],
                formatter: function(value) {
                    return Math.round(value) + '人';
                }
            },
            geo: {
                map: 'china',
                roam: true,  // 允许缩放和漫游
                scaleLimit: {
                    min: 0.8,
                    max: 3
                },
                zoom: 1.1,
                center: [105, 36],
                itemStyle: {
                    normal: {
                        areaColor: '#0f172a',  // 改为更深的蓝黑色
                        borderColor: '#1e40af', // 深蓝边框
                        borderWidth: 1.5,
                        shadowColor: 'rgba(30, 64, 175, 0.3)',
                        shadowBlur: 10
                    },
                    emphasis: {
                        areaColor: '#1e40af',  // 悬浮时的深蓝色
                        borderColor: '#60a5fa',
                        borderWidth: 3,
                        shadowColor: 'rgba(59, 130, 246, 0.8)',
                        shadowBlur: 20
                    }
                },
                label: {
                    normal: {
                        show: false,  // 默认显示省市名称
                        textStyle: {
                            color: '#e2e8f0',
                            fontSize: 11,
                            fontWeight: 'bold',
                            textShadowColor: 'rgba(0, 0, 0, 0.8)',
                            textShadowBlur: 2
                        }
                    },
                    emphasis: {
                        show: true,
                        textStyle: {
                            color: '#ffffff',
                            fontSize: 14,
                            fontWeight: 'bold',
                            textShadowColor: 'rgba(30, 64, 175, 0.8)',
                            textShadowBlur: 3
                        }
                    }
                }
            },
            series: [
                {
                    name: '人员分布',
                    type: 'map',
                    map: 'china',
                    geoIndex: 0,
                    data: data,
                    itemStyle: {
                        normal: {
                            borderColor: '#1e40af',
                            borderWidth: 1.5,
                            shadowColor: 'rgba(30, 64, 175, 0.3)',
                            shadowBlur: 5
                        },
                        emphasis: {
                            borderColor: '#60a5fa',
                            borderWidth: 3,
                            shadowColor: 'rgba(96, 165, 250, 0.6)',
                            shadowBlur: 15
                        }
                    },
                    label: {
                        normal: {
                            show: true,
                            textStyle: {
                                color: '#e2e8f0',
                                fontSize: 11,
                                fontWeight: 'bold',
                                textShadowColor: 'rgba(0, 0, 0, 0.8)',
                                textShadowBlur: 2
                            }
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                color: '#ffffff',
                                fontSize: 14,
                                fontWeight: 'bold',
                                textShadowColor: 'rgba(30, 64, 175, 0.8)',
                                textShadowBlur: 3
                            }
                        }
                    }
                }
            ]
        };
        
        // 使用notMerge选项提高性能
        myChart.setOption(option, { notMerge: true, silent: false });
        
        // 添加点击事件
        myChart.off('click'); // 先移除之前的事件监听器
        myChart.on('click', function (params) {
            if (params.data && params.data.value !== undefined) {
                console.log('点击了:', params.name, '人员数量:', params.data.value);
                // 可以在这里添加更多交互功能
            } else {
                console.log('点击了:', params.name, '暂无数据');
            }
        });
    };

    // 如果已经有缓存，直接使用
    if (chinaMapCache) {
        renderChart(chinaMapCache);
    } else {
        // 首次加载时缓存地图数据
        fetch('/中华人民共和国.json')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(geoJson => {
                chinaMapCache = geoJson; // 缓存地图数据
                renderChart(geoJson);
            })
            .catch(error => {
                console.error('加载地图数据失败:', error);
                // 添加错误提示
                const errorOption = {
                    title: {
                        text: '地图加载失败',
                        left: 'center',
                        top: 'center',
                        textStyle: {
                            color: '#ef4444',
                            fontSize: 18
                        }
                    }
                };
                myChart.setOption(errorOption);
            });
    }
}

export {
    setPie,
    setLineChart,
    setLiquidfill,
    setScoreRank,
    setThroryPie,
    setRank,
    setLine,
    setGradientLine,
    setRadarChart,
    setTaskProgress,
    setTendencyChart,
    setIntelligenceRadarChart,
    setRoundPie,
    setPieChart,
    setULineChart,
    setChinaMap,
}